import React, { useState, useEffect, useCallback } from 'react';
import {
  View,
  Text,
  StyleSheet,
  TouchableOpacity,
  ScrollView,
  ActivityIndicator,
  Alert,
  Dimensions,
  ToastAndroid,
} from 'react-native';
import { DeviceEventEmitter, NativeModules } from 'react-native';
import { useNavigation, useFocusEffect } from '@react-navigation/native';
import { StackNavigationProp } from '@react-navigation/stack';
import { RootStackParamList } from '../../App';

import { Card, ServerInfo } from '../types/Card';
import { CardGrid } from '../components/CardGrid';
import { TabBar } from '../components/TabBar';
import { ActionBar } from '../components/ActionBar';
import { useFocusManager } from '../hooks/useFocusManager';
import APIService from '../services/api';
import NetworkDiscoveryService from '../services/NetworkDiscovery';
import DatabaseService from '../services/DatabaseService';

const { width, height } = Dimensions.get('window');

type TabType = 'local' | string;

export const MainScreen: React.FC = () => {
  const navigation = useNavigation<StackNavigationProp<RootStackParamList>>();
  // 状态管理
  const [loading, setLoading] = useState(true);
  const [error, setError] = useState('');
  const [activeTab, setActiveTab] = useState<TabType>('local');
  const [discoveredDevices, setDiscoveredDevices] = useState<ServerInfo[]>([]);
  const [localCards, setLocalCards] = useState<Card[]>([]);
  const [deviceCards, setDeviceCards] = useState<Map<string, Card[]>>(new Map());
  const [isRefreshing, setIsRefreshing] = useState(false);
  const [isScanning, setIsScanning] = useState(false);
  const [showCardImages, setShowCardImages] = useState(true);
  const [shuffledCards, setShuffledCards] = useState<Map<string, Card[]>>(new Map());
  const [currentIndex, setCurrentIndex] = useState(0);
  const [focusedCardId, setFocusedCardId] = useState<number | null>(null);
  const [focusedButtonIndex, setFocusedButtonIndex] = useState<number | null>(null);
  const [focusedTabIndex, setFocusedTabIndex] = useState<number | null>(null);
  const [isRefreshingCards, setIsRefreshingCards] = useState(false);


  // 焦点管理器
  const focusManager = useFocusManager({
    onTabChange: (index) => {
      const tabs = ['local', ...discoveredDevices.map(d => d.ip)];
      const selectedTab = tabs[index];
      console.log('焦点管理器 Tab 切换:', selectedTab);
      setActiveTab(selectedTab);
      
      // 如果是远程设备且还没有加载卡片，则自动加载
      if (selectedTab !== 'local') {
        const device = discoveredDevices.find(d => d.ip === selectedTab);
        if (device) {
          const existingCards = deviceCards.get(selectedTab);
          if (!existingCards || existingCards.length === 0) {
            console.log(`🔄 焦点管理器自动加载设备 ${selectedTab} 的卡片...`);
            loadDeviceCards(device, false);
          } else {
            // 如果已有卡片，更新焦点管理器的卡片列表
            console.log(`📦 焦点管理器：设备 ${selectedTab} 已有 ${existingCards.length} 张卡片，更新焦点管理器`);
            focusManager.updateCards(existingCards);
          }
        }
      } else {
        // 切换到本地，更新焦点管理器的卡片列表
        console.log(`📦 焦点管理器：切换到本地，更新焦点管理器，共 ${localCards.length} 张卡片`);
        focusManager.updateCards(localCards);
      }
    },
    onCardSelect: (index) => {
      const currentCards = activeTab === 'local' ? localCards : deviceCards.get(activeTab) || [];
      if (currentCards[index]) {
        // 设置焦点卡片ID
        setFocusedCardId(currentCards[index].id);
        handleCardPress(currentCards[index], index);
      }
    },
    onAction: (action) => {
      switch (action) {
        case 'refresh':
          handleRefresh();
          break;
        case 'scan':
          handleScanNetwork();
          break;
        case 'random':
          // 随机排列卡片
          const currentCards = activeTab === 'local' ? localCards : deviceCards.get(activeTab) || [];
          if (currentCards.length > 0) {
            const shuffled = [...currentCards].sort(() => Math.random() - 0.5);
            setShuffledCards(prev => new Map(prev).set(activeTab, shuffled));
            setCurrentIndex(0);
            console.log('🎲 卡片已随机排列');
          }
          break;
        case 'toggle':
          // 切换图片/文字显示
          setShowCardImages(!showCardImages);
          console.log(`🖼️ 切换到${!showCardImages ? '图片' : '文字'}显示`);
          break;
      }
    },
    onFocusChange: (focusState) => {
      if (focusState.currentElement === 'tab') {
        setFocusedCardId(null);
        setFocusedButtonIndex(null);
        setFocusedTabIndex(focusState.tabIndex);
        console.log(`🎯 焦点切换到 Tab: ${focusState.tabIndex}`);
      } else if (focusState.currentElement === 'card') {
        const currentCards = activeTab === 'local' ? localCards : deviceCards.get(activeTab) || [];
        if (currentCards[focusState.cardIndex]) {
          setFocusedCardId(currentCards[focusState.cardIndex].id);
          setFocusedButtonIndex(null);
          setFocusedTabIndex(null);
          console.log(`🎯 焦点切换到卡片: ${currentCards[focusState.cardIndex].id}`);
        }
      } else if (focusState.currentElement === 'button') {
        setFocusedCardId(null);
        setFocusedButtonIndex(focusState.currentIndex);
        setFocusedTabIndex(null);
        console.log(`🎯 焦点切换到按钮: ${focusState.currentIndex}`);
      } else {
        setFocusedCardId(null);
        setFocusedButtonIndex(null);
        setFocusedTabIndex(null);
      }
    },
  });

  // 更新焦点管理器的 tabs 列表
  useEffect(() => {
    const tabs = ['local', ...discoveredDevices.map(d => d.ip)];
    focusManager.updateTabs(tabs);
  }, [discoveredDevices, focusManager]);

  // 监听 activeTab 变化，更新焦点管理器的卡片列表
  useEffect(() => {
    // 如果正在刷新，不更新焦点管理器的卡片列表，避免焦点状态变化
    if (isRefreshingCards) {
      console.log('🔄 正在刷新中，跳过焦点管理器卡片列表更新');
      return;
    }
    
    // 添加防抖，避免频繁更新
    const updateTimeout = setTimeout(() => {
      if (activeTab === 'local') {
        console.log(`📦 activeTab 变化：切换到本地，更新焦点管理器，共 ${localCards.length} 张卡片`);
        focusManager.updateCards(localCards);
      } else {
        const currentCards = deviceCards.get(activeTab) || [];
        console.log(`📦 activeTab 变化：切换到设备 ${activeTab}，更新焦点管理器，共 ${currentCards.length} 张卡片`);
        focusManager.updateCards(currentCards);
      }
    }, 200); // 200ms 防抖延迟
    
    return () => {
      clearTimeout(updateTimeout);
    };
  }, [activeTab, localCards, deviceCards, isRefreshingCards]); // 移除 focusManager 依赖项

  // 初始化应用
  useEffect(() => {
    initializeApp();
    startNativeDiscovery();
  }, []);

  // 监听卡片删除事件
  useEffect(() => {
    const cardDeletedUnsubscribe = DatabaseService.onCardDeleted((result: any) => {
      console.log('🗑️ 卡片删除事件:', result);
      // 刷新本地卡片列表
      refreshLocalCards();
    });

    return () => {
      cardDeletedUnsubscribe.remove();
    };
  }, []);

  // 每次屏幕获得焦点时重新获取本机数据
  useFocusEffect(
    useCallback(() => {
      let isMounted = true;
      let refreshTimeout: NodeJS.Timeout;

      const refreshLocalData = async () => {
        try {
          console.log('🔄 屏幕获得焦点，刷新本机数据...');
          const localCardsData = await DatabaseService.getLocalCards();
          if (isMounted) {
            setLocalCards(localCardsData);
            console.log('✅ 本机数据已刷新，共', localCardsData.length, '张卡片');
          }
        } catch (error) {
          console.error('❌ 刷新本机数据失败:', error);
        }
      };
      
      // 添加防抖，避免频繁刷新
      refreshTimeout = setTimeout(refreshLocalData, 500);
      
      return () => {
        isMounted = false;
        if (refreshTimeout) {
          clearTimeout(refreshTimeout);
        }
      };
    }, [])
  );

  // 刷新本地卡片列表
  const refreshLocalCards = async () => {
    try {
      console.log('🔄 刷新本地卡片列表...');
      const localCardsData = await DatabaseService.getLocalCards();
      setLocalCards(localCardsData);
      console.log('✅ 本地卡片列表已更新，共', localCardsData.length, '张卡片');
    } catch (error) {
      console.error('❌ 刷新本地卡片列表失败:', error);
    }
  };

  // 初始化应用
  const initializeApp = async () => {
    try {
      setLoading(true);
      setError('');
      
      // 加载本地数据
      const localCardsData = await DatabaseService.getLocalCards();
      setLocalCards(localCardsData);
      
      // 后台扫描网络设备，不阻塞界面显示
      scanNetwork().catch(console.error);
    } catch (error) {
      console.error('初始化应用失败:', error);
      setLocalCards([]);
    } finally {
      setLoading(false);
    }
  };

  // 启动原生网络发现
  const startNativeDiscovery = async () => {
    try {
      const { UDPDiscoveryModule } = NativeModules;
      
      await UDPDiscoveryModule.startDiscovery();
      
      const deviceUnsubscribe = DeviceEventEmitter.addListener('onBabyTapMobileDiscovered', (data: any) => {
        if (!data?.host || !data?.port) return;
        
        const serverInfo: ServerInfo = {
          ip: data.host,
          port: data.port,
          url: data.url || `https://${data.host}:${data.port}`,
          isHttps: data.isHttps !== false
        };
        
        console.log('📡 发现新设备:', serverInfo);
        
        setDiscoveredDevices(prev => {
          const exists = prev.some(d => d.ip === data.host && d.port === data.port);
          if (!exists) {
            // 立即加载设备卡片
            setTimeout(() => {
              console.log(`🔄 开始加载设备 ${serverInfo.ip} 的卡片...`);
              loadDeviceCards(serverInfo, false);
            }, 500);
            return [...prev, serverInfo];
          }
          return prev;
        });
      });
      
      return () => {
        deviceUnsubscribe.remove();
        UDPDiscoveryModule.stopDiscovery();
      };
    } catch (error) {
      console.error('启动原生网络发现失败:', error);
    }
  };

  // 扫描网络
  const scanNetwork = async () => {
    try {
      console.log('🔍 开始扫描网络...');
      console.log('⏰ 等待 BabyTapMobile 发送广播（每30秒一次）...');
      
      // 等待 UDP 发现，不主动扫描
      // 网络发现现在主要依赖 UDP 广播监听
    } catch (error) {
      console.error('扫描网络失败:', error);
      setError('扫描网络失败');
    }
  };

  // 加载设备卡片
  const loadDeviceCards = async (device: ServerInfo, forceRefresh = false) => {
    try {
      console.log(`🔄 开始加载设备 ${device.ip} 的卡片...`);
      console.log(`📡 设备信息:`, device);
      
      // 清除之前的错误状态
      setError('');
      
      const existingCards = deviceCards.get(device.ip);
      if (!forceRefresh && existingCards && existingCards.length > 0) {
        console.log(`📦 设备 ${device.ip} 已有 ${existingCards.length} 张卡片，跳过加载`);
        return;
      }

      // 先设置服务器
      APIService.setServer(device);
      console.log(`✅ API 服务器已设置为: ${device.url}`);
      
      // 先进行健康检查
      try {
        console.log(`🏥 检查设备 ${device.ip} 健康状态...`);
        const healthResult = await APIService.healthCheck();
        console.log(`✅ 设备 ${device.ip} 健康检查通过:`, healthResult);
      } catch (healthError) {
        console.warn(`⚠️ 设备 ${device.ip} 健康检查失败:`, healthError);
        // 健康检查失败不影响卡片加载，继续尝试
      }
      
      const cardsData = await APIService.getCards();
      console.log(`📥 从设备 ${device.ip} 加载了 ${cardsData.length} 张卡片`);
      
      // 为每个卡片添加 serverInfo
      const cardsWithServerInfo = cardsData.map((card: Card) => ({
        ...card,
        serverInfo: device
      }));
      
      setDeviceCards(prev => {
        const newMap = new Map(prev);
        newMap.set(device.ip, cardsWithServerInfo);
        console.log(`✅ 设备 ${device.ip} 卡片已更新到状态中`);
        return newMap;
      });
      
      // 如果当前激活的 tab 是这个设备，更新焦点管理器的卡片
      if (activeTab === device.ip) {
        focusManager.updateCards(cardsWithServerInfo);
      }
      
    } catch (err) {
      console.error(`❌ 加载设备 ${device.ip} 卡片失败:`, err);
      setDeviceCards(prev => {
        const newMap = new Map(prev);
        newMap.set(device.ip, []);
        return newMap;
      });
      
      // 显示错误提示
      if (activeTab === device.ip) {
        setError(`无法连接到设备 ${device.ip}，请检查网络连接`);
      }
    }
  };

  // 刷新处理
  const handleRefresh = async () => {
    setIsRefreshing(true);
    setIsRefreshingCards(true);
    setError(''); // 清除错误状态
    
    try {
      console.log(`🔄 开始刷新 ${activeTab === 'local' ? '本地' : '远程'} 卡片...`);
      
      if (activeTab === 'local') {
        const localCardsData = await DatabaseService.getLocalCards();
        setLocalCards(localCardsData);
        console.log(`✅ 本地卡片刷新完成，共 ${localCardsData.length} 张卡片`);
      } else {
        const device = discoveredDevices.find(d => d.ip === activeTab);
        if (device) {
          console.log(`🔄 强制刷新设备 ${activeTab} 的卡片...`);
          await loadDeviceCards(device, true);
          console.log(`✅ 设备 ${activeTab} 卡片刷新完成`);
        } else {
          console.error(`❌ 未找到设备 ${activeTab}`);
          setError(`未找到设备 ${activeTab}`);
        }
      }
    } catch (error) {
      console.error('刷新失败:', error);
      setError('刷新失败，请重试');
    } finally {
      setIsRefreshing(false);
      setIsRefreshingCards(false);
      console.log('🔄 刷新完成，焦点保持在刷新按钮上');
    }
  };

  const handleCardPress = (card: Card, index: number) => {
    const currentCards = activeTab === 'local' ? localCards : deviceCards.get(activeTab) || [];
    const serverInfo = activeTab === 'local' ? undefined : discoveredDevices.find(d => d.ip === activeTab);
    
    navigation.navigate('CardDetail', {
      card,
      isLocal: activeTab === 'local',
      serverInfo,
      cardList: currentCards,
      currentIndex: index,
      showCardImages, // 传递当前的显示模式
    });
  };

  const handleScanNetwork = async () => {
    try {
      setIsScanning(true);
      setError('');
      
      console.log('🔍 开始 UDP 发现模式...');
      console.log('⏰ 等待 BabyTapMobile 发送广播（最多35秒）...');
      
      // 手动启动 UDP 发现模块
      try {
        const { UDPDiscoveryModule } = NativeModules;
        if (UDPDiscoveryModule) {
          console.log('✅ UDP 发现模块可用，启动监听...');
          await UDPDiscoveryModule.startDiscovery();
        } else {
          console.log('❌ UDP 发现模块不可用');
        }
      } catch (udpError) {
        console.error('启动 UDP 发现失败:', udpError);
      }
      
      const servers = await NetworkDiscoveryService.scanNetwork();
      
      if (servers.length > 0) {
        // 自动选择最佳服务器
        const bestServer = NetworkDiscoveryService.autoSelectServer();
        if (bestServer) {
          setDiscoveredDevices(prev => {
            const exists = prev.some(d => d.ip === bestServer.ip && d.port === bestServer.port);
            if (!exists) {
              setTimeout(() => loadDeviceCards(bestServer), 1000);
              return [...prev, bestServer];
            }
            return prev;
          });
          
          console.log('✅ 自动连接到服务器:', bestServer);
          ToastAndroid.show(`已连接到服务器: ${bestServer.ip}:${bestServer.port}`, ToastAndroid.SHORT);
        }
      } else {
        console.log('⏰ UDP 监听超时，未发现 BabyTapMobile 设备');
        setError('未发现 BabyTapMobile 设备');
      }
    } catch (error) {
      console.error('扫描网络失败:', error);
      setError('扫描网络失败');
    } finally {
      setIsScanning(false);
    }
  };

  // 渲染空状态
  const renderEmptyState = () => {
    const currentCards = activeTab === 'local' ? localCards : deviceCards.get(activeTab) || [];
    const device = discoveredDevices.find(d => d.ip === activeTab);
    
    return (
      <View style={styles.emptyContainer}>
        <Text style={styles.emptyText}>
          {activeTab === 'local' ? '暂无本地卡片' : '暂无远程卡片'}
        </Text>
        <Text style={styles.emptySubText}>
          {activeTab === 'local' 
            ? '请从远程设备下载卡片到本地' 
            : `设备: ${device?.ip || activeTab}\n端口: ${device?.port || '未知'}`
          }
        </Text>
        {activeTab !== 'local' && (
          <Text style={styles.emptySubText}>
            请确保 BabyTapMobile 设备正在运行并已连接网络
          </Text>
        )}
        {error && (
          <Text style={[styles.emptySubText, { color: '#ff6b6b', marginTop: 10 }]}>
            错误: {error}
          </Text>
        )}
      </View>
    );
  };

  // 渲染Tab内容
  const renderTabContent = () => {
    let currentCards: Card[] = [];
    
    if (activeTab === 'local') {
      currentCards = localCards;
    } else {
      currentCards = deviceCards.get(activeTab) || [];
    }

    // 检查是否有随机排列的卡片
    const shuffledCardsForTab = shuffledCards.get(activeTab);
    if (shuffledCardsForTab && shuffledCardsForTab.length > 0) {
      currentCards = shuffledCardsForTab;
    }
    
    return (
      <View style={styles.tabContent}>
        {/* 卡片网格显示 */}
        {currentCards.length > 0 ? (
          <CardGrid
            cards={currentCards}
            onCardPress={(card) => {
              const index = currentCards.findIndex(c => c.id === card.id);
              handleCardPress(card, index);
            }}
            serverInfo={activeTab === 'local' ? undefined : discoveredDevices.find(d => d.ip === activeTab)}
            showImages={showCardImages}
            focusedCardId={focusedCardId}
          />
        ) : (
          renderEmptyState()
        )}
      </View>
    );
  };

  // 渲染加载状态
  if (loading) {
    return (
      <View style={styles.loadingContainer}>
        <ActivityIndicator size="large" color="#4a90e2" />
        <Text style={styles.loadingText}>正在加载...</Text>
      </View>
    );
  }

  // 渲染错误状态
  if (error) {
    return (
      <View style={styles.errorContainer}>
        <Text style={styles.errorText}>错误: {error}</Text>
        <TouchableOpacity style={styles.retryButton} onPress={initializeApp}>
          <Text style={styles.retryButtonText}>重试</Text>
        </TouchableOpacity>
      </View>
    );
  }



  // 主界面
  return (
    <View style={styles.container}>
      {/* 顶部导航栏 - Tab左对齐，按钮右对齐 */}
      <View style={styles.topNavigationBar}>
        {/* 左侧Tab区域 */}
        <View style={styles.tabSection}>
          <TabBar
            tabs={['local', ...discoveredDevices.map(d => d.ip)]}
            activeTab={activeTab}
            onTabPress={(tab) => {
              console.log('Tab 被点击:', tab);
              setActiveTab(tab);
              
              // 如果是远程设备且还没有加载卡片，则自动加载
              if (tab !== 'local') {
                const device = discoveredDevices.find(d => d.ip === tab);
                if (device) {
                  const existingCards = deviceCards.get(tab);
                  if (!existingCards || existingCards.length === 0) {
                    console.log(`🔄 手动点击加载设备 ${tab} 的卡片...`);
                    loadDeviceCards(device, false);
                  } else {
                    // 如果已有卡片，更新焦点管理器的卡片列表
                    console.log(`📦 设备 ${tab} 已有 ${existingCards.length} 张卡片，更新焦点管理器`);
                    focusManager.updateCards(existingCards);
                  }
                }
              } else {
                // 切换到本地，更新焦点管理器的卡片列表
                console.log(`📦 切换到本地，更新焦点管理器，共 ${localCards.length} 张卡片`);
                focusManager.updateCards(localCards);
              }
            }}
            focusedTabIndex={focusedTabIndex}
          />
        </View>

        {/* 右侧按钮区域 */}
        <View style={styles.buttonSection}>
          <TouchableOpacity 
            style={[
              styles.topButton, 
              isScanning && styles.topButtonDisabled,
              focusedButtonIndex === 0 && styles.topButtonFocused
            ]} 
            disabled={isScanning}
          >
            {isScanning ? (
              <ActivityIndicator size="small" color="#ffffff" />
            ) : (
              <Text style={[
                styles.topButtonText,
                focusedButtonIndex === 0 && styles.topButtonTextFocused
              ]}>🔍 扫描</Text>
            )}
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={[
              styles.topButton, 
              isRefreshing && styles.topButtonDisabled,
              focusedButtonIndex === 1 && styles.topButtonFocused
            ]} 
            disabled={isRefreshing}
          >
            {isRefreshing ? (
              <ActivityIndicator size="small" color="#ffffff" />
            ) : (
              <Text style={[
                styles.topButtonText,
                focusedButtonIndex === 1 && styles.topButtonTextFocused
              ]}>↻ 刷新</Text>
            )}
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={[
              styles.topButton,
              focusedButtonIndex === 2 && styles.topButtonFocused
            ]} 
          >
            <Text style={[
              styles.topButtonText,
              focusedButtonIndex === 2 && styles.topButtonTextFocused
            ]}>🎲 随机</Text>
          </TouchableOpacity>
          
          <TouchableOpacity 
            style={[
              styles.topButton,
              focusedButtonIndex === 3 && styles.topButtonFocused
            ]} 
          >
            <Text style={[
              styles.topButtonText,
              focusedButtonIndex === 3 && styles.topButtonTextFocused
            ]}>
              {showCardImages ? '📝 文字' : '🖼️ 图片'}
            </Text>
          </TouchableOpacity>
        </View>
      </View>

      {/* 主内容区域 */}
      <ScrollView style={styles.mainContainer} contentContainerStyle={styles.scrollContent}>
        {renderTabContent()}
      </ScrollView>
    </View>
  );
};

const styles = StyleSheet.create({
  container: {
    flex: 1,
    backgroundColor: '#1a1a1a',
  },
  mainContainer: {
    flex: 1,
    backgroundColor: '#1a1a1a',
  },
  loadingContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a1a1a',
  },
  loadingText: {
    color: '#ffffff',
    fontSize: 18,
    marginTop: 20,
  },
  errorContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: '#1a1a1a',
  },
  errorText: {
    color: '#ff6b6b',
    fontSize: 18,
    marginBottom: 20,
  },
  retryButton: {
    backgroundColor: '#4a90e2',
    paddingHorizontal: 20,
    paddingVertical: 10,
    borderRadius: 8,
  },
  retryButtonText: {
    color: '#ffffff',
    fontSize: 16,
    fontWeight: 'bold',
  },

  tabContent: {
    flex: 1,
  },
  statusBar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    paddingHorizontal: 20,
    paddingVertical: 15,
    backgroundColor: '#2a2a2a',
    borderBottomWidth: 1,
    borderBottomColor: '#444',
  },
  statusText: {
    color: '#ffffff',
    fontSize: 18,
    fontWeight: 'bold',
  },
  emptyContainer: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    paddingHorizontal: 40,
  },
  emptyText: {
    color: '#ffffff',
    fontSize: 20,
    fontWeight: 'bold',
    marginBottom: 10,
  },
  emptySubText: {
    color: '#cccccc',
    fontSize: 16,
    textAlign: 'center',
  },
  scrollContent: {
    flexGrow: 1,
  },

  topNavigationBar: {
    flexDirection: 'row',
    justifyContent: 'space-between',
    alignItems: 'center',
    backgroundColor: '#2a2a2a',
    borderBottomWidth: 1,
    borderBottomColor: '#444',
  },
  tabSection: {
    flex: 1,
  },
  buttonSection: {
    flexDirection: 'row',
    gap: 10,
    paddingRight: 20,
  },
  topButton: {
    backgroundColor: '#4a90e2',
    paddingHorizontal: 15,
    paddingVertical: 8,
    borderRadius: 6,
  },
  topButtonDisabled: {
    backgroundColor: '#666666',
  },
  topButtonFocused: {
    backgroundColor: '#5a9ee2',
    borderColor: '#ffffff',
    borderWidth: 2,
    shadowColor: '#ffffff',
    shadowOffset: {
      width: 0,
      height: 0,
    },
    shadowOpacity: 0.5,
    shadowRadius: 5,
    elevation: 6,
  },
  topButtonText: {
    color: '#ffffff',
    fontSize: 14,
    fontWeight: 'bold',
  },
  topButtonTextFocused: {
    color: '#ffffff',
    fontWeight: 'bold',
  },
}); 